//
//  LEEOAuthController.swift
//  SinaWeibo
//
//  Created by 李江波 on 2016/11/15.
//  Copyright © 2016年 lijiangbo. All rights reserved.
//

import UIKit
import SVProgressHUD


let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! + "/userInfo.plist"


class LEEOAuthController: UIViewController {

    let webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(dismissVc))
        
        //发布的时候一定要删掉
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .plain, target: self, action: #selector(autoUser))
        
        requestcode()
        
        
        
    }
    
    /// 请求授权
    private func requestcode() {
    
        let urlStr = "https://api.weibo.com/oauth2/authorize" + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        webView.loadRequest(URLRequest(url: URL(string: urlStr)!))

    }

    @objc private func dismissVc() {
    
        self.dismiss(animated: true, completion: nil)
    }
    
    @objc private func autoUser() {
    
        let jsString = "document.getElementById('userId').value = '15712691251', document.getElementById('passwd').value = 'li789456123'"
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    
    //解决卡死退出菊花还转问题
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        SVProgressHUD.dismiss()
    }

}

extension LEEOAuthController : UIWebViewDelegate {

    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //一般协议方法返回值为bool类型 如果返回true 就可以正常工作否则就不能够正常工作
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlStr = request.url?.absoluteString ?? ""
        let codeStr = "code="
        if urlStr.contains(codeStr) {
            
            //拿到code
            let str = request.url?.query ?? ""
            let code = (str as NSString).substring(from: codeStr.characters.count)
            
            print(code)
            
            LEEOAuthViewModel.shared.getAccess_token(code, completion: { (isSuccess) in
                
                if isSuccess {
                
                    //发送通知
                    NotificationCenter.default.post(name: NSNotification.Name(ChangeRootViewController), object: "welcomeVc")
                    
                }else{
                
                    SVProgressHUD.showError(withStatus: "网络不好哦，重试啊啊啊")
                }
            })
            
            return false
        }
        return true
    }
    


}









